package com.logistic.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.logistic.dao.HibernateSessionFactory;
import com.logistic.dao.IntegralDao;
import com.logistic.domain.Integral;
import com.logistic.domain.User;

public class IntegralDaoImpl extends HibernateDaoSupport implements IntegralDao {
	
	@SuppressWarnings("finally")
	public int save(Integral in) {

		Session s = HibernateSessionFactory.getSession();
		Transaction t = s.beginTransaction();
		
		s.saveOrUpdate(in);
		try {
			t.commit();
		} catch (Exception e) {
			
		} finally {
			HibernateSessionFactory.closeSession();
			return 1;
		}
	}
	@SuppressWarnings("finally")
	public int modify(Integral in) {
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			
			
			String sql = "update Integral inte set ";
			if(in.getPoint() != null && !"".equals(in.getPoint())){
				sql = sql + "inte.Point='"+in.getPoint()+"', ";
			}
			if(in.getUsedPoints() != null && !"".equals(in.getUsedPoints())){
				sql = sql + "inte.usedPoints='"+in.getUsedPoints()+"', ";
			}
			if(in.getaccoutMoney() != null && !"".equals(in.getaccoutMoney())){
				sql = sql + "inte.accoutMoney='"+in.getaccoutMoney()+"', ";
			}
			if(in.getUsedMoney() != null && !"".equals(in.getUsedMoney())){
				sql = sql + "inte.usedMoney='"+in.getUsedMoney()+"', ";
			}
			
			sql = (String)sql.subSequence(0, sql.length()-2);
			Query q = s.createQuery(sql
					+ " where inte.Uid=?"); 
			
			q.setParameter(0, in.getUid());
			
			q.executeUpdate();
			t.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally
		{
			HibernateSessionFactory.closeSession();
			return 1;
		}
	}
	
	public void delete(String id) {
		try{
		Session s = HibernateSessionFactory.getSession();
		Transaction tran = s.beginTransaction();
		Query q = s.createQuery("delete from Integral where Uid=?");
		q.setParameter(0, id);
		q.executeUpdate();
		tran.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	

 

	public Integral getIntegralByUid(Integral in){
		Integral newIn = null;
		try{
		Session s = HibernateSessionFactory.getSession();
		Transaction t = s.beginTransaction();
		
		String hql = "from Integral integral where integral.Uid =?";
		Query q = s.createQuery(hql);
		q.setParameter(0, in.getUid());
		List list = q.list();
		t.commit();
		if(list.isEmpty() || list.size()==0) {
			return null;
		}
		newIn = (Integral)list.get(0);
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return newIn;
	}
	
}
